package ava8;

import java.util.Arrays;
import java.util.Comparator;

public class LambdaTest {

	public static void Lambda1(String[] arr) {
		System.out.println("直接Arrays.sort");
		Arrays.sort(arr);			//原始按字母顺序排序
		for(String a:arr) {
			System.out.print(a+"\t");
		}
	}
	public static void Lambda2(String[] arr) {
		System.out.println("调用Comparator接口的comparable方法");
		Arrays.sort(arr,new LengthDescComparator());		//需要new对象，增大内存消耗
		for(String a:arr) {
			System.out.print(a+"\t");
		}
	}
	//传递方法/代码块(函数式编程)Java8
	public static void Lambda3(String[] arr) {
		System.out.println("Lambda比较长度");
		//原理：调用Comparator接口的comparable方法
		//Arrays.sort(arr,(String s1,String s2)->s1.length()-s2.length());
		//Arrays.sort(arr,(s1,s2)->s1.length()-s2.length());		//类型可省略
		Arrays.sort(arr,(s1,s2) -> (-1)*(s1.length()-s2.length()));	//长度大->小
		for(String a:arr) {
			System.out.print(a+"\t");
		}
	}


	public static void main(String[] args) {
		String[] arr = new String[] {
				"Mercury", "Venus", "Earth", "Mars",
				"Jupiter", "Saturn", "Uranus",
				"Neptune"
		};
		System.out.println("原字符数组");
		for(String a:arr) {
			System.out.print(a+"\t");
		}

		System.out.println();
		Lambda1(arr);

		System.out.println();
		Lambda2(arr);

		System.out.println();
		Lambda3(arr);
	}

}

class LengthDescComparator implements Comparator<String> {

	@Override
	public int compare(String first, String second) {
		//获取2个字符串长度
		int len1 = (first==null? 0 : first.length());
		int len2 = (first==null? 0 : second.length());

		//如果len1 == len2，返回0，表示两个字符串相等
		//如果len1 >  len2，返回正数，表示first>second
		//如果len1 <  len2，返回负数，表示first<second
		return (-1) * (len1 - len2);	//长度大->小
	}

}